﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Xwltz.Framework.Helper
{
    public class CaptchaHelper
    {
        #region 初始化参数

        /// <summary>
        /// 验证码的最大长度
        /// </summary>
        public int MaxLength => 10;

        /// <summary>
        /// 验证码的最小长度
        /// </summary>
        public int MinLength => 1;

        #endregion

        #region 生成4个随机数
        public string RandCode()
        {
            const int codeCount = 4; //生成4个随机数
            //var randomChar = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z"; //数字字母混合
            var randomChar = "0,1,2,3,4,5,6,7,8,9";//纯数字
            randomChar = randomChar.Replace(",", "");
            var randomCode = "";
            System.Threading.Thread.Sleep(3);
            var allCharArray = randomChar.ToCharArray();
            var n = allCharArray.Length;
            var random = new Random(~unchecked((int)DateTime.Now.Ticks));
            for (var i = 0; i < codeCount; i++)
            {
                var rnd = random.Next(0, n);
                randomCode += allCharArray[rnd];
            }
            return randomCode;
        }
        #endregion

        #region 验证码--方式1

        ///  <summary>
        ///  验证码--方式1 创建验证码图片
        ///  </summary>
        ///  <param  name="randomCode">验证码</param>
        public byte[] CreateImage1(string randomCode)
        {
            const int randAngle = 40; //随机转动角度
            var mapwidth = randomCode.Length * 18;
            var map = new Bitmap(mapwidth, 24);//创建图片背景
            var graph = Graphics.FromImage(map);
            graph.Clear(Color.White);//清除画面，填充背景
            //graph.DrawRectangle(new Pen(Color.Silver, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框

            var rand = new Random();

            //验证码旋转，防止机器识别
            var chars = randomCode.ToCharArray();//拆散字符串成单字符数组
            //文字距中
            var format = new StringFormat(StringFormatFlags.NoClip)
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };

            //画图片的背景噪音线
            for (var i = 0; i < 2; i++)
            {
                var x1 = rand.Next(10);
                var x2 = rand.Next(map.Width - 10, map.Width);
                var y1 = rand.Next(map.Height);
                var y2 = rand.Next(map.Height);

                graph.DrawLine(new Pen(c[rand.Next(7)]), x1, y1, x2, y2);
            }

            foreach (var t in chars)
            {
                var cindex = rand.Next(7);
                var f = new Font("Arial", 18, FontStyle.Regular);//字体样式(参数2为字体大小)
                Brush b = new SolidBrush(c[cindex]);
                var dot = new Point(12, 16);
                float angle = rand.Next(-randAngle, randAngle);//转动的度数
                graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
                graph.RotateTransform(angle);
                graph.DrawString(t.ToString(), f, b, 1, 1, format);
                graph.RotateTransform(-angle);//转回去
                graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
            }
            //生成图片
            var stream = new MemoryStream();
            map.Save(stream, ImageFormat.Jpeg);
            graph.Dispose();
            map.Dispose();
            return stream.ToArray();
        }

        #endregion

        #region 验证码--方式2

        /// <summary>
        /// 验证码--方式2
        /// </summary>
        /// <param name="randomCode">验证码</param>
        /// <returns></returns>
        public byte[] CreateImage2(string randomCode)
        {
            //颜色列表，用于验证码、噪线、噪点  
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码  
            string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
            var rnd = new Random();
            var bmp = new Bitmap(100, 40);
            var g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线  
            for (var i = 0; i < 3; i++)
            {
                var x1 = rnd.Next(100);
                var y1 = rnd.Next(40);
                var x2 = rnd.Next(100);
                var y2 = rnd.Next(40);
                var clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串  
            for (var i = 0; i < randomCode.Length; i++)
            {
                var fnt = font[rnd.Next(font.Length)];
                var ft = new Font(fnt, 18);
                var clr = color[rnd.Next(color.Length)];
                g.DrawString(randomCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, 8);
            }
            //画噪点  
            for (var i = 0; i < 20; i++)
            {
                var x = rnd.Next(bmp.Width);
                var y = rnd.Next(bmp.Height);
                var clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }

            var ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
            finally
            {
                //显式释放资源  
                bmp.Dispose();
                g.Dispose();
            }
        }

        #endregion

        #region 验证码--方式3

        /// <summary>
        /// 验证码--方式3
        /// </summary>
        /// <param name="randomCode">验证码</param>
        public byte[] CreateImage3(string randomCode)
        {
            var image = new Bitmap((int)Math.Ceiling(randomCode.Length * 12.0), 22);
            var g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                var random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (var i = 0; i < 25; i++)
                {
                    var x1 = random.Next(image.Width);
                    var x2 = random.Next(image.Width);
                    var y1 = random.Next(image.Height);
                    var y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                var font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(randomCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (var i = 0; i < 100; i++)
                {
                    var x = random.Next(image.Width);
                    var y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                var stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public string CreateValidateCode(int length)
        {
            var randMembers = new int[length];
            var validateNums = new int[length];
            var validateNumberStr = "";
            //生成起始序列值
            var seekSeek = unchecked((int)DateTime.Now.Ticks);
            var seekRand = new Random(seekSeek);
            var beginSeek = seekRand.Next(0, int.MaxValue - length * 10000);
            var seeks = new int[length];
            for (var i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (var i = 0; i < length; i++)
            {
                var rand = new Random(seeks[i]);
                var pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, int.MaxValue);
            }
            //抽取随机数字
            for (var i = 0; i < length; i++)
            {
                var numStr = randMembers[i].ToString();
                var numLength = numStr.Length;
                var rand = new Random();
                var numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = int.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (var i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }

        /// <summary>
        /// 得到验证码图片的长度
        /// </summary>
        /// <param name="validateNumLength">验证码的长度</param>
        /// <returns></returns>
        public static int GetImageWidth(int validateNumLength)
        {
            return (int)(validateNumLength * 12.0);
        }

        /// <summary>
        /// 得到验证码的高度
        /// </summary>
        /// <returns></returns>
        public static double GetImageHeight()
        {
            return 22.5;
        }

        #endregion
    }
}